<template>
	<view class="page">
		<view class="" style="flex: 1;">
			<!-- <up-navbar title="" @rightClick="{}" :autoBack="true" bgColor="#fff" placeholder></up-navbar> -->
			<view class="flex column box-sizing width-full paddingTop-30 paddingBottom-30">
				<view class="flex flex-center items-center marginBottom-30">
					<view class="flex flex-center items-center" style="">
						<up-upload :deletable="false" :fileList="fileList1" @afterRead="afterRead" @delete="deletePic"
							width="150rpx" height="150rpx" name="1" :maxCount="1">
							<image v-if="fileList1" :src="userInfo.avatar?userInfo.avatar:userA" mode=""
								style="box-sizing: border-box; border: 2px solid #fff; width: 150rpx; height: 150rpx;border-radius: 15px;">
							</image>
						</up-upload>
					</view>
				</view>

				<up-cell-group :customStyle="{'background-color':'#fff'}">
					<up-cell @click="cellClick(0)" :value="form.username" title="昵称" isLink></up-cell>
					<!-- <up-cell @click="form.mobile?'':cellClick(1)" :value = "form.mobile" title="手机号" :isLink = "form.mobile?false:true" ></up-cell> -->
					<up-cell @click="form.mobile?'':cellClick(1)" :value="form.mobile" title="手机号"
						:isLink="form.mobile?false:true"></up-cell>
					<up-cell @click="cellClick(2)" :value="form.grade_name" title="年级" isLink></up-cell>
					<up-cell @click="showArea = true" :value="form.area" title="区域" isLink>
					</up-cell>
					<up-cell title="学校">
						<template #right-icon>
							<up-input placeholder="请输入所在学校" v-model="form.school" border="none"
								inputAlign='right'></up-input>
						</template>
					</up-cell>
					<up-cell title="班级">
						<template #right-icon>
							<up-input placeholder="请输入所在班级" v-model="form.class" border="none"
								inputAlign='right'></up-input>
						</template>
					</up-cell>
				</up-cell-group>
				<!-- <view class="width-full height-20"></view>
				<up-cell-group :customStyle = "{'background-color':'#fff'}">
					<up-cell @click="cellClick(3)" :value = "form.yingbiaoName" title="音标" isLink></up-cell>
					<up-cell @click="cellClick(4)" :value = "form.yuyinName" title="语音" isLink></up-cell>
					<up-cell @click="cellClick(5)" :value = "form.cixingName" title="词性" isLink></up-cell>
				</up-cell-group> -->
				<view class="width-full height-20"></view>
				<up-cell-group :customStyle="{'background-color':'#fff'}">
					<!-- <up-cell @click="cellClick(6)" :value = "form.moshiName" title="记词模式" isLink></up-cell> -->
					<up-cell @click="cellClick(3)" :value="form.master==1?'好':'差'" title="程度" isLink></up-cell>
				</up-cell-group>
			</view>
			<up-picker :show="showArea" :columns="pickerColumns" @change="onPickerChange" @close="showArea = false"
				@confirm="confirmArea" :defaultIndex="defaultindex" @cancel="showArea = false"
				ref='PickerRef'></up-picker>

						<up-picker closeOnClickOverlay keyName="label" :show="pickerShow" :columns="lists[defaultCell+'List']"
				@close="pickerShow = false" @cancel="pickerShow = false" @confirm="pickerChange"></up-picker>
		<!-- 	<up-picker closeOnClickOverlay keyName="label" :show="pickerShow" :columns="lists['masterList']"
				@close="pickerShow = false" @cancel="pickerShow = false" @confirm="pickerChange"
				:defaultIndex="findSelectedIndex()">
			</up-picker> -->
		</view>
		<up-modal :show="editShow" showCancelButton @close="cancel" @cancel="cancel" @confirm="setTitle" :title="title">
			<view class="slot-content">
				<up-input maxlength="11" v-model="form[defaultCell]" border="bottom" placeholder="请输入"></up-input>
			</view>
		</up-modal>
		<up-popup round="5" :show="phoneShow" @close="close" @open="open">
			<view class="popupBox">
				<view class="flex">
					<up-image shape="circle" mode="widthFix" :src="logo" width="80rpx" height="80rpx"></up-image>
					<view class="flex column marginLeft-20 width-full">
						<view class="fontSize-28 weight-700">
							百霸智育
						</view>
						<view class="fontSize-26">
							绑定后查看学习数据信息
						</view>
					</view>
				</view>
				<view class="marginTop-30">
					<view class="">
						<up-input maxlength="11" placeholder="请输入手机号" border="surround"
							v-model="loginForm.mobile"></up-input>
					</view>
					<view class="marginTop-30">
						<up-input placeholder="请输入您的验证码" v-model="loginForm.code">
							<template #suffix>
								<up-code ref="uCodeRef" @change="codeChange" seconds="60" changeText="X秒重新获取"></up-code>
								<up-button @tap="getCode" :text="tips" type="primary" size="mini"></up-button>
							</template>
						</up-input>
					</view>
					<view class="marginTop-30 flex items-center">
						<!-- 	<up-radio-group v-model="loginForm.isRadiu">
							<up-radio shape="circle" label=""></up-radio>
						</up-radio-group> -->
						<up-checkbox :customStyle="{marginBottom: '8px'}" label="" shape="circle" size="16px" usedAlone
							v-model:checked="loginForm.isRadiu">
						</up-checkbox>
						<view class="fontSize-28">
							您是否已阅读并同意<span>《用户协议》</span>和<span>《隐私政策》</span>
						</view>
					</view>

				</view>
				<view class="width-full box-sizing btns flex column items-center flex-center">
					<view class="marginTop-30 flex flex-center" style="width: 80vw;">
						<up-button @click="bindPhone" size="normal" type="primary" text="绑定手机"></up-button>
					</view>
				</view>
			</view>
		</up-popup>
		<view class="width-full box-sizing btn2 flex column items-center flex-center">
			<view class="flex flex-center">
				<view class="save-btn" @click="btnClick">
					保存
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		inject,
		reactive,
		watch
	} from 'vue';
	import {
		onReady,
		onLoad,

	} from '@dcloudio/uni-app'
	import image from '@/static/logo.png'
	import {
		regionData
	} from 'element-china-area-data';
	const updateWordSet = inject('updateWordSet');
	const getConfigSetApi = inject('getConfigSet');
	const getUserInfoApi = inject('getUserInfo');
	const getUserInfoNewApi = inject('getUserInfoNew');
	const updateUserInfoNewApi = inject('updateUserInfoNew');
	const loginMobileApi = inject('loginMobile');
	const updateUserInfoApi = inject('updateUserInfo');
	const updateAvatarApi = inject('updateAvatar');
	const $uploadHttp = inject('$uploadHttp');
	const sendSmsApi = inject('sendSms');
	const userA = ref('https://cdn.uviewui.com/uview/album/1.jpg');
	const logo = ref(image);
	const fileList1 = ref([]);
	const editShow = ref(false);
	const phoneShow = ref(false);
	const title = ref('');
	const tips = ref('');
	const uCodeRef = ref(null)
	const loginForm = ref({
		mobile: '',
		code: '',
		isRadiu: false,
	});
	const userInfo = ref({})
	const form = ref({})
	const defaultCell = ref('')
	const pickerShow = ref(false)
	const lists = ref({
		grade_idList: [
			[
				
			]
		],
		masterList: [
			[{
					label: '好',
					value: 1
				},
				{
					label: '差',
					value: 2
				},
			]
		],

	})
	const showArea = ref(false);
	const defaultindex = ref([0, 0, 0]);
	const pickerColumns = ref([])
	const getUserInfo = () => {
		let param = uni.getStorageSync('loginParam');
		getUserInfoNewApi().then(res => {
			uni.setStorageSync('userInfo', res)
			userInfo.value = res
			form.value.username = userInfo.value.username
			form.value.mobile = userInfo.value.mobile
			form.value.class = userInfo.value.class
			form.value.area = userInfo.value.area
			form.value.school = userInfo.value.school
			form.value.grade_id = userInfo.value.memberset.grade_id
			form.value.grade_name = userInfo.value.memberset.grade_name
			form.value.master = userInfo.value.memberset.master
		})
	};
	getUserInfo();
	onLoad(() => {
		let first = regionData.map((item) => {
			return item.label;
		})
		let second = regionData[0].children.map((item) => {
			return item.label;
		})

		let third = regionData[0].children[0].children.map((item) => {
			return item.label;
		})

		pickerColumns.value = [first, second, third];
		defaultindex.value = uni.getStorageSync('defaultindex');
		console.log('defaultindex', defaultindex)

	})
	//年级定位
	const findSelectedIndex = () => {
		const grade_idList = lists.value.grade_idList[0];
		console.log(grade_idList,233)
		if (form.value.grade_name) {
			const index = grade_idList.findIndex(item => item.label == form.value.grade_name);
			return index !== -1 ? [index] : null;
		} else {
			return null;
		}
	};
	watch(form, (newValue) => {
		findSelectedIndex();
	}, {
		deep: true
	});

	const onchange = (e) => {
		const value = e.detail.value
	}
	const onnodeclick = (node) => {

	}




	// const getConfigSet = () => {
	// 	getConfigSetApi().then(res => {
	// 		let keys = Object.keys(res['grade_ids']);
	// 		// console.log(keys, 'oooooooooo')
	// 		for (let s of keys) {
	// 			// lists.value['grade_idList'] = ;
	// 			let obj = {
	// 				label: res['grade_ids'][s],
	// 				value: s
	// 			}

	// 			lists.value['grade_idList'][0].push(obj)
	// 		}
	// 		// console.log(lists.value, 'oooooooooo')
	// 	})
	// };
	const getConfigSet = () => {
		getConfigSetApi().then(res => {
			const grade_ids = res['grade_ids'];
			console.log(grade_ids,265)
			// 用于存储合并后的数据
			const combinedList = [];

			// 遍历grade_ids的每个外层键对应的内层对象
			for (const outerKey in grade_ids) {
				const innerObj = grade_ids[outerKey];

				// 遍历内层对象的每个属性值并添加到合并列表
				for (const innerKey in innerObj) {
					const obj = {
						label: innerObj[innerKey],
						value: innerKey
					};
					combinedList.push(obj);
				}
			}
			console.log(combinedList,279)
			lists.value['grade_idList'][0] = combinedList;
			console.log(lists.value['grade_idList'][0])

		});
	};
	getConfigSet();
	const cellClick = (id) => {
		console.log(id,286)
		let datas = ['username', 'mobile', 'grade_id', 'master']
		defaultCell.value = datas[id]
		console.log(defaultCell.value,289)
		// pickerShow.value = true
		if (id > 1) {
			pickerShow.value = true
		} else {
			id == 0 ? title.value = '昵称修改' : title.value = '手机号修改'
			id == 0 ? editShow.value = true : phoneShow.value = true
		}

	}
	const pickerChange = (e) => {
		// console.log(e.value[0].label, 22222222)
		if (e.value && e.value[0]) {
			form.value[defaultCell.value] = e.value[0].value
			defaultCell.value == 'grade_id' ? form.value['grade_name'] = e.value[0].label : ''
			// form.value[defaultCell.value+"Name"] = e.value[0].label
		}
		pickerShow.value = false

	}
	const updateWordSetFun = (param) => {
		updateWordSet(param).then(res => {
			// console.log(res, 666666)
			if (param.type == 'studymoshi') {
				setTimeout(() => {
					uni.navigateBack();
				}, 200)
			}
		})
	}

	const onPickerChange = (e) => {

		if (e.columnIndex == 0) {
			let second = regionData[e.index].children.map((item) => {
				return item.label;
			})
			pickerColumns.value[1] = second;
			let third = regionData[e.indexs[0]].children[e.indexs[1]].children.map((item) => {
				return item.label;
			})
			defaultindex.value = [e.indexs[0], 0, 0]
			pickerColumns.value[2] = third;
		} else if (e.columnIndex == 1) {
			let third = regionData[e.indexs[0]].children[e.indexs[1]].children.map((item) => {
				return item.label;
			})
			defaultindex.value = [e.indexs[0], e.indexs[1], 0]
			pickerColumns.value[2] = third;
		}
	}

	const confirmArea = (e) => {
		console.log(e);
		form.value['area'] = e.value.join()
		showArea.value = false
		defaultindex.value = e.indexs
	}





	const uPickerRef = ref(null)
	const changeHandler = (e) => {
		const {
			columnIndex,
			value,
			values,
			index,
		} = e;

		if (columnIndex === 0) {
			uPickerRef.value.setColumnValues(1, columnData[index]);
		}
	}

	const confirm = (e) => {
		// console.log('confirm', e);
		form.value['area'] = e.value.join()
		showArea.value = false;
	};
	const cancel = () => {
		editShow.value = false
	}
	const setTitle = () => {
		const mobileRegex = /^1[3-9]\d{9}$/;
		if (!form.value.mobile && defaultCell.value == 'mobile' || !mobileRegex.test(form.value.mobile) && defaultCell
			.value == 'mobile') {
			return uni.showToast({
				title: '手机号格式错误！',
				icon: 'none'
			})
		}
		if (!form.value.username && defaultCell.value == 'username' || form.value.username == '' && defaultCell
			.value == 'username') {
			return uni.showToast({
				title: '昵称不能为空！',
				icon: 'none'
			})
		}
		editShow.value = false
	}
	const editAvatar = () => {
		updateAvatarApi({
			avatar: fileList1.value[0].url
		}).then(res => {
			// console.log(res, 545454)
		})
	}
	// 删除图片
	const deletePic = (event) => {
		fileList1.value.splice(event.index, 1);
	};

	// 新增图片
	const afterRead = async (event) => {
		// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
		let lists = [].concat(event.file);
		let fileListLen = fileList1.value.length;
		lists.map((item) => {
			fileList1.value.push({
				...item,
				status: 'uploading',
				message: '上传中',
			});
		});
		// console.log(lists, 'listslistslistslistslists')
		for (let i = 0; i < lists.length; i++) {
			const result = await uploadFilePromise(lists[i].url);
			// console.log(result, 'resultresultresultresult')
			let item = fileList1.value[fileListLen];
			fileList1.value.splice(fileListLen, 1, {
				...item,
				status: 'success',
				message: '',
				url: result,
			});
			editAvatar(result);
			fileListLen++;
		}
	};
	const uploadFilePromise = (url) => {
		return new Promise((resolve, reject) => {
			let a = uni.uploadFile({
				url: $uploadHttp, // 仅为示例，非真实的接口地址
				filePath: url,
				name: 'file',
				formData: {
					user: 'test',
				},
				success: (res) => {
					setTimeout(() => {
						resolve(res.data ? JSON.parse(res.data).data : {});
					}, 1000);
				},
			});
		});
	};
	const close = () => {
		phoneShow.value = false
		loginForm.value.mobile = ''
		loginForm.value.code = ''
	}
	const open = () => {
		phoneShow.value = true
	}
	const codeChange = (text) => {
		tips.value = text;
	};
	const getCode = () => {
		const mobileRegex = /^1[3-9]\d{9}$/;
		if (!loginForm.value.mobile || !mobileRegex.test(loginForm.value.mobile)) {
			return uni.showToast({
				title: '手机号格式错误！',
				icon: 'none'
			})
		}
		// console.log(uCodeRef, uCodeRef.value, 'sssssssssssss')
		if (uCodeRef.value.canGetCode) {
			// 模拟向后端请求验证码
			uni.showLoading({
				title: '正在获取验证码',
			});
			sendSmsApi({
				mobile: loginForm.value.mobile
			}).then(res => {
				uni.showToast({
					title: '验证码已发送！',
					icon: 'none'
				})
				// console.log(res, 'asdas')
				uni.hideLoading();
				uCodeRef.value.start();
				if (res && res.is_fs == 0) {
					loginForm.value.code = res.code
				}
			})
		} else {
			// uni.$u.toast('倒计时结束后再发送');
		}
	};
	// 登录
	const bindPhone1 = () => {
		// uni.navigateTo({
		// 	url:'/pages/index/memoryWordGuide'
		// })
	}
	const loginMobile = () => {
		loginMobileApi({
			mobile: loginForm.value.mobile,
			code: loginForm.value.code
		}).then(es => {
			form.value.mobile = loginForm.value.mobile
			uni.setStorageSync('userInfo', es.data)
			uni.setStorageSync('token', es.token);
			loginForm.value.mobile = ''
			loginForm.value.code = ''
			phoneShow.value = false
			// getUserInfo();
		})
	}
	const bindPhone = () => {
		const mobileRegex = /^1[3-9]\d{9}$/;
		if (!loginForm.value.mobile || loginForm.value.mobile == '') {
			return uni.showToast({
				title: '请先填写手机号！',
				icon: 'none'
			})
		}

		if (!loginForm.value.mobile || !mobileRegex.test(loginForm.value.mobile)) {
			return uni.showToast({
				title: '手机号格式错误！',
				icon: 'none'
			})
		}
		if (!loginForm.value.code || loginForm.value.code == '') {
			return uni.showToast({
				title: '请先填写验证码！',
				icon: 'none'
			})
		}
		if (!loginForm.value.isRadiu) {
			uni.showModal({
				title: '提示',
				content: `您是否已阅读并同意《用户协议》和《隐私政策》？`,
				success: function(res) {
					if (res.confirm) {
						loginForm.value.isRadiu = true
						loginMobile()
					} else if (res.cancel) {
						console.log('用户点击取消');
					}
				}
			})
		} else {
			loginMobile()
		}



	}
	// 保存设置按钮
	const btnClick = () => {
		// console.log(3333333333)
		updateUserInfoNewApi(form.value).then(res => {
			// console.log(res, 'aaaaaaaaaaaaaa');
			uni.setStorageSync('userInfo', res.data)
			uni.setStorageSync('defaultindex', defaultindex.value);
			uni.navigateBack()
		})
		// uni.navigateBack()
	}
</script>

<style lang="scss" scoped>
	.page {
		flex: 1;
		background-color: #f1f1f1;
	}

	.btn2 {
		padding-bottom: 50rpx;
		margin-top: 30rpx;
		margin-bottom: 20rpx;
	}

	@media (max-height: 800px) {
		.btn2 {
			padding-bottom: 0;
			margin-top: 0;
		}

		.page {}
	}



	.btns {
		padding-bottom: calc(50rpx);
	}

	.popupBox {
		width: 100vw;
		padding: 50rpx 30rpx 30rpx;
		background-color: #fff;
		box-sizing: border-box;

		.btns {
			padding-bottom: calc(50rpx);
		}
	}


	.save-btn {
		width: 702rpx;
		height: 104rpx;
		line-height: 104rpx;
		background: #51D580;
		border-radius: 92rpx;
		text-align: center;
		color: #fff;
		font-size: 32rpx;
	}
</style>